package com.zhs;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListener;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

public class Consumer {
    public static void main(String[]args) throws Exception {
        DefaultMQPushConsumer consumer=new DefaultMQPushConsumer("consumer_group");
        consumer.setNamesrvAddr("192.168.0.241:9876");
        //制定消费者从什么位置消费
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
        //订阅topic_java主题下所有消息
        consumer.subscribe("topic_java","*");

        consumer.registerMessageListener((List<MessageExt> list,ConsumeConcurrentlyContext context)->{
            for(MessageExt ext:list){
                try {
                    System.out.println(new Date()+":"+new String(ext.getBody(),"utf-8"));
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            return ConsumeConcurrentlyStatus.RECONSUME_LATER;
        });
        //必须start后才能使用
        consumer.start();
        System.out.println("consumer 已经启动");
    }
}
